﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DMS.Logic
{
    public class Document
    {
		DBStorage _storage;
		const int _bufferSize = 1024 * 1024 * 50;

		#region Properties

		public int FolderId { get; internal set; }

		public DateTime CreationDate { get; internal set; }

		public bool IsCheckedOut { get; private set; }

		public int DocumentTypeID { get; set; }

		public int NumberOfDownloads { get; private set; }

		public int NumberOfRatings { get; private set; }

		public int TotalRatings { get; private set; }

		public string OriginalFileName { get; internal set; }

		public string Name { get; set; }

		public int DocumentId { get; set; }

		internal int lastVersionId { get; set; }

		

		#endregion

		public void Save()
        {
			var dal = DAL.DALclass.getInstance();
			DAL.Document doc = new DMS.DAL.Document();
			doc.Folder = dal.getFolderById(this.FolderId);
			doc.Name = this.Name;
			doc.OriginalFileName = this.OriginalFileName;
			doc.CreationDate = DateTime.Now;

			this.DocumentId = dal.AddDocument(doc);

			DAL.DocumentVersion version = new DMS.DAL.DocumentVersion();
			version.Document = doc;
			version.VersionNumber = 1;
			version.VaresionDate = DateTime.Now;
			version.ProviderData = "";
			version.User = BL.getInstance().getUserById(1);

			lastVersionId = dal.SaveVersion(version);


		
        }

        internal void Write(Stream input)
        {
			BinaryReader reader = new BinaryReader(input);

			_storage = new DBStorage(this.lastVersionId, "");
			
			byte[] buffer = new byte[_bufferSize];

			int red = 0;

			do
			{
				red = reader.Read(buffer, 0, _bufferSize);
				if(red>0)
					_storage.Write(buffer, red);
			}
			while (red > 0);
	

	
        }

        public void Dispose()
        {

        }
    }
}
